package com.commit.shiro;

import com.commit.domain.User;
import com.commit.service.QuestionService;
import com.commit.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义Realm完成用户的认证和授权
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private QuestionService questionService;

    @Override
    public String getName() {
        return "userRealm";
    }

    // 支持什么类型的token
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {

        // 从token中 获取用户身份信息
        String loginName = (String) token.getPrincipal();
        User sysUser = userService.findByName(loginName);
        // 拿username从数据库中查询
        // 如果查询不到则返回null
        if (sysUser == null) {
            return null;
        }

        // 获取从数据库查询出来的用户密码
        String password = sysUser.getPassword();

        // 构建用户身份信息
        User activeUser = new User();
        activeUser.setId(sysUser.getId());
        activeUser.setLoginName(sysUser.getLoginName());
        activeUser.setUsername(sysUser.getUsername());

        // 返回认证信息由父类AuthenticatingRealm进行认证，将用户认证信息传入
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                activeUser, password, getName());

        return simpleAuthenticationInfo;
    }

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        return  null;
    }

}
